package com.fuled.test.tool_config;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @author hcy
 * 获取客户端的真实IP地址
 */
public class IPUtilsPerformanceTool {

    /**
     * 获取客户端的真实IP地址
     *
     * @param request HttpServletRequest对象
     * @return 客户端的IP地址，如果无法获取，则返回null
     */
    public static String getClientIP(HttpServletRequest request) {
        if(request == null) return "请求为null";
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP值之间以逗号分隔
        if (ip != null && ip.length() > 15) { // "XXX.XXX.XXX.XXX".length() = 15
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }
}